package com.newtype.meeting.server.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.jdo.PersistenceManager;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.newtype.meeting.client.model.Degree;
import com.newtype.meeting.client.model.Title;
import com.newtype.meeting.client.service.TitleService;
import com.newtype.meeting.server.PMF;

@SuppressWarnings("serial")
public class TitleServiceImpl extends RemoteServiceServlet implements
		TitleService {

	@Override
	public void addTitle(Title title) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(title);
		} finally {
			pm.close();
		}
	}

	@Override
	public void deleteTitle(String id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Title toDeleteTitle = pm.getObjectById(Title.class, id);
			pm.deletePersistent(toDeleteTitle);
		} finally {
			pm.close();
		}
	}

	@Override
	public Title getTitle(String id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		return pm.getObjectById(Title.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public ArrayList<Title> getTitles() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			List<Title> titles = (List<Title>) pm.newQuery(Title.class)
					.execute();
			ArrayList<Title> toReturn = new ArrayList<Title>(pm
					.detachCopyAll(titles));
			for (Title title : toReturn)
				title.updateProperties();
			return toReturn;
		} finally {
			pm.close();
		}
	}

	@Override
	public ArrayList<Degree> getDegrees() {
		//获得所有职称的list集合
		List<Title> titleList = getTitles();
		//将职称等级封装到set集合中
		Set<Integer> degreeSet = new HashSet<Integer>();
		for (Title title : titleList) {
			degreeSet.add(title.getDegree());
		}
		ArrayList<Degree> toReturn = new ArrayList<Degree>();
		Degree degree = null;
		Iterator<Integer> it = degreeSet.iterator();
		while (it.hasNext()) {
			degree = new Degree();
			degree.setDegreeID(it.next());
			toReturn.add(degree);
		}
		for (Degree d : toReturn) {
			d.updateProperties();
		}
		return toReturn;
	}

}
